from flask import render_template, g, redirect, request, jsonify, current_app, session, abort

from info import db, constants
from info.models import User, Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu

@profile_blu.route('/info')
@user_login_data
def center():
    """
    个人中心
    :return:
    """
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html',data=data)


@profile_blu.route('/base_info',methods=['GET','POST'])
@user_login_data
def base_info():
    """基本资料设置"""
    user = g.user
    data = {
        'user': user.to_dict()
    }
    if request.method =='GET':
        return render_template('news/user_base_info.html',data=data)

    # 1、获取参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 2、校验参数
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    if gender not in ['MAN','WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 3、保存到数据库
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.commit()
    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库存储失败')
    # 修改session中存储的值
    session['nick_name'] = nick_name
    # 返回响应
    return jsonify(errno=RET.OK,errmsg='更新操作成功')

@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    """
    头像设置
    :return:
    """
    user = g.user

    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html',data=data)
    # 获取图片路径
    # 1、获取参数
    try:
        avatar_file = request.files.get('avatar').read()  # 获取上传图像的路径
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 将文件上传到七牛云
    try:
        avatar_url = storage(avatar_file)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
    # 更新数据库里图片地址
    user.avatar_url = avatar_url
    data = {
        'avatar_url': constants.QINIU_DOMIN_PREFIX+avatar_url
    }
    # 返回响应
    return jsonify(errno=RET.OK,errmsg='更新操作成功',data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    """
    密码设置
    :return:
    """
    user = g.user
    if request.method=='GET':
        return render_template('news/user_pass_info.html')

    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 校验参数
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 校验密码
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg='原始密码输入错误')

    # 修改数据库用户表中密码
    user.password = new_password

    # 返回响应
    return jsonify(errno=RET.OK,errmsg='更新操作成功')


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    """新闻收藏页展示"""
    user = g.user
    # 获取参数
    page = request.args.get('p',1)
    # 校验参数
    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        p = 1
    # 查询用户收藏的新闻列表
    collection_list = []
    total_page = 1
    current_page = 1
    try:
        news = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        total_page = news.pages
        current_page = news.page
        collection_list = news.items
    except Exception as a:
        current_app.logger.error(a)

    collection_dict = [ collection.to_basic_dict() for collection in collection_list]
    data = {
        'total_page':total_page,
        'current_page':current_page,
        'collection_dict':collection_dict
    }

    return render_template('news/user_collection.html',data=data)

@profile_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    """
    新闻发布
    :return:
    """
    user = g.user
    if request.method == 'GET':
        category = []
        try:
            category = Category.query.all()
        except Exception as a:
            current_app.logger.error(a)
        category_dict = [item.to_dict() for item in category]
        category_dict.pop(0)
        data = {
            "category_dict": category_dict
        }
        return render_template('news/user_news_release.html',data=data)
    # 1、获取参数 使用form表单提交
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = "个人发布"
    # 2、校验参数
    if not all([title,category_id,digest,index_image,content,source]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 3、获取图片地址
    try:
        image_url = index_image.read()
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DATAERR,errmsg='获取地址错误')

    # 4、将图片上传到七牛云
    try:
        key = storage(image_url)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片错误')

    # 5、初始化新闻模型，将数据存入数据库
    news = News()
    news.source =source
    news.content=content
    news.digest=digest
    news.title=title
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = user.id
    news.status = 1  # 当前新闻状态 如果为0代表审核通过，1代表审核中，-1代表审核不通过
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DBERR, errmsg='存储数据失败')
    return jsonify(errno=RET.OK,errmsg='提交成功，等待审核')



@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """个人中心新闻列表"""
    user = g.user
    page = request.args.get('p')
    # 查询当前用户发布的新闻信息，分页显示
    total_page = 1
    current_page = 1
    news_li = []
    try:
        news = News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_li = news.items
        total_page = news.pages
        current_page = news.page
    except Exception as a:
        current_app.logger.error(a)
    news_dict = [ new.to_review_dict() for new in news_li]
    data = {
        'total_page':total_page,
        'current_page':current_page,
        'news_dict':news_dict
    }

    return  render_template('news/user_news_list.html')

@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """我的关注页面内容"""
    # 将用户关注的作者信息返回
    user = g.user
    page = request.args.get('p')
    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1
    users = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.followed.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
        users = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as a:
        current_app.logger.error(a)
    user_list = [ user_li.to_dict() for user_li in users]
    data = {
        'total_page':total_page,
        'current_page':current_page,
        'user_list':user_list
    }


    return  render_template('news/user_follow.html',data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """其他用户页面"""
    user = g.user
    # 获取其他用户
    user_id = request.args.get('user_id')
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as a:
        current_app.logger.error(a)
    if not other:
        abort(404)
    # 判断该用户是否被关注
    is_followed = False
    if user:
        if other in user.followed:
            is_followed = True
    data = {
        'user': user.to_dict(),
        'other':other.to_dict(),
        'is_followed':is_followed
    }
    return render_template('news/other.html', data = data)

@profile_blu.route('/other_news_list')
def other_news_list():
    """其他用户发表的新闻列表页"""
    page = request.args.get('p')
    user_id = request.args.get('user_id')
    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1
    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    news_dict = [ news.to_review_dict() for news in news_li]
    data = {
        'current_page':current_page,
        "total_page":total_page,
        'news_dict':news_dict
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

